package com.zhentao.PollutionPredictio.controller;

import com.zhentao.PollutionPredictio.model.service.IChemicalFactoryService;
import com.zhentao.PollutionPredictio.model.mapper.ChemicalFactoryMapper;
import com.zhentao.PollutionPredictio.service.PollutionPredictionAiService;
import com.zhentao.pojo.ChemicalFactory;
import com.zhentao.util.Enum.ApiServiceExceptionEnum;
import com.zhentao.util.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 污染预测模块控制器
 * 提供六个核心功能的API接口
 */
@RestController
@RequestMapping("/pollution-prediction")
@CrossOrigin(origins = "*")
public class PollutionPredictionController {

    @Autowired
    private PollutionPredictionAiService aiService;

    @Autowired
    @Qualifier("chemicalFactoryServiceImpl")
    private IChemicalFactoryService chemicalFactoryService;

    @Autowired
    private ChemicalFactoryMapper chemicalFactoryMapper;

    /**
     * 1. 化工厂分析
     * POST /pollution-prediction/factory-analysis/{factoryId}
     */
    @PostMapping("/factory-analysis/{factoryId}")
    public ResultVo analyzeFactory(@PathVariable Long factoryId) {
        try {
            // 获取工厂信息
            ChemicalFactory factory = chemicalFactoryService.findAllFactory().stream()
                .filter(f -> f.getFactoryId().equals(factoryId))
                .findFirst()
                .orElse(null);

            if (factory == null) {
                return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
            }

            // 调用AI分析
            String analysisResult = aiService.analyzeChemicalFactory(factory);

            Map<String, Object> result = new HashMap<>();
            result.put("factoryId", factoryId);
            result.put("factoryName", factory.getFactoryName());
            result.put("analysisResult", analysisResult);
            result.put("timestamp", System.currentTimeMillis());

            return ResultVo.success(result);
        } catch (Exception e) {
            return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
        }
    }

    /**
     * 2. 扩散路径定位
     * POST /pollution-prediction/diffusion-path/{factoryId}
     */
    @PostMapping("/diffusion-path/{factoryId}")
    public ResultVo predictDiffusionPath(@PathVariable Long factoryId, @RequestBody Map<String, Object> weatherData) {
        try {
            String pathResult = aiService.predictDiffusionPath(factoryId, weatherData);

            // 生成地理可视化数据
            Map<String, Object> geoData = generateGeoVisualizationData(factoryId, weatherData);
            System.out.println("生成的地理数据: " + geoData);

            Map<String, Object> result = new HashMap<>();
            result.put("factoryId", factoryId);
            result.put("weatherData", weatherData);
            result.put("diffusionPath", pathResult);
            result.put("geoData", geoData); // 添加地理数据
            result.put("timestamp", System.currentTimeMillis());

            System.out.println("返回的完整结果: " + result);

            return ResultVo.success(result);
        } catch (Exception e) {
            return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
        }
    }

    /**
     * 3. 污染预测模型
     * POST /pollution-prediction/predict/{factoryId}
     */
    @PostMapping("/predict/{factoryId}")
    public ResultVo predictPollution(@PathVariable Long factoryId,
                                   @RequestParam(defaultValue = "24") int predictionHours,
                                   @RequestBody Map<String, Object> currentData) {
        try {
            String predictionResult = aiService.predictPollutionTrend(factoryId, predictionHours, currentData);

            Map<String, Object> result = new HashMap<>();
            result.put("factoryId", factoryId);
            result.put("predictionHours", predictionHours);
            result.put("currentData", currentData);
            result.put("predictionResult", predictionResult);
            result.put("timestamp", System.currentTimeMillis());

            return ResultVo.success(result);
        } catch (Exception e) {
            return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
        }
    }

    /**
     * 4. 风险评估报告
     * POST /pollution-prediction/risk-assessment/{factoryId}
     */
    @PostMapping("/risk-assessment/{factoryId}")
    public ResultVo generateRiskAssessment(@PathVariable Long factoryId, @RequestBody Map<String, Object> riskFactors) {
        try {
            String assessmentResult = aiService.generateRiskAssessment(factoryId, riskFactors);

            Map<String, Object> result = new HashMap<>();
            result.put("factoryId", factoryId);
            result.put("riskFactors", riskFactors);
            result.put("assessmentReport", assessmentResult);
            result.put("timestamp", System.currentTimeMillis());

            return ResultVo.success(result);
        } catch (Exception e) {
            return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
        }
    }

    /**
     * 5. 预警机制
     * POST /pollution-prediction/early-warning/{factoryId}
     */
    @PostMapping("/early-warning/{factoryId}")
    public ResultVo generateEarlyWarning(@PathVariable Long factoryId,
                                       @RequestParam double currentLevel,
                                       @RequestParam double threshold) {
        try {
            String warningResult = aiService.generateEarlyWarning(factoryId, currentLevel, threshold);

            Map<String, Object> result = new HashMap<>();
            result.put("factoryId", factoryId);
            result.put("currentLevel", currentLevel);
            result.put("threshold", threshold);
            result.put("exceedRatio", currentLevel / threshold);
            result.put("warningResult", warningResult);
            result.put("timestamp", System.currentTimeMillis());

            return ResultVo.success(result);
        } catch (Exception e) {
            return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
        }
    }

    /**
     * 6. 影响评估
     * POST /pollution-prediction/impact-evaluation/{factoryId}
     */
    @PostMapping("/impact-evaluation/{factoryId}")
    public ResultVo assessImpact(@PathVariable Long factoryId,
                                @RequestParam String impactArea,
                                @RequestBody Map<String, Object> sensitiveTargets) {
        try {
            String impactResult = aiService.assessImpact(factoryId, impactArea, sensitiveTargets);

            Map<String, Object> result = new HashMap<>();
            result.put("factoryId", factoryId);
            result.put("impactArea", impactArea);
            result.put("sensitiveTargets", sensitiveTargets);
            result.put("impactAssessment", impactResult);
            result.put("timestamp", System.currentTimeMillis());

            return ResultVo.success(result);
        } catch (Exception e) {
            return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
        }
    }
    /**
     * 批量AI分析接口 - 新增
     * 一次性分析风险因素、周边环境、历史事故
     * POST /pollution-prediction/batch-ai-analysis/{factoryId}
     */
    @PostMapping("/batch-ai-analysis/{factoryId}")
    public ResultVo batchAIAnalysis(@PathVariable Long factoryId, @RequestBody Map<String, Object> requestData) {
        try {
            System.out.println("开始批量AI分析，工厂ID: " + factoryId);
            System.out.println("请求数据: " + requestData);

            // 获取位置数据
            Map<String, Object> locationData = (Map<String, Object>) requestData.get("locationData");
            if (locationData == null) {
                return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
            }

            // 获取工厂信息
            String factoryName = (String) locationData.get("factoryName");
            Object latObj = locationData.get("latitude");
            Object lngObj = locationData.get("longitude");

            // 生成模拟的AI分析结果
            Map<String, String> analysisResult = new HashMap<>();

            // 风险因素分析
            analysisResult.put("riskFactors",
                    "基于工厂位置分析（" + latObj + ", " + lngObj + "），主要风险因素包括：\n" +
                            "1. 化学品泄漏风险 - 工厂储存和使用化学原料，存在泄漏风险\n" +
                            "2. 大气污染排放 - 生产过程中可能产生有害气体排放\n" +
                            "3. 土壤污染风险 - 长期生产可能对周边土壤造成污染\n" +
                            "4. 水体污染风险 - 废水处理不当可能影响周边水体\n" +
                            "5. 噪声污染 - 生产设备运行产生的噪声影响");

            // 周边环境分析
            analysisResult.put("surroundingEnvironment",
                    "周边环境分析（基于坐标：" + latObj + ", " + lngObj + "）：\n\n" +
                            "1. 500米范围内：\n" +
                            "   - 居民区：约200户居民\n" +
                            "   - 商业区：小型商店和餐饮店\n" +
                            "   - 道路交通：主要道路通行\n\n" +
                            "2. 1000米范围内：\n" +
                            "   - 学校：1所小学，约500名学生\n" +
                            "   - 医院：1所社区医院\n" +
                            "   - 公园：小型社区公园\n\n" +
                            "3. 2000米范围内：\n" +
                            "   - 水源保护区：距离最近水源地1.8公里\n" +
                            "   - 农田：部分农业用地\n" +
                            "   - 工业区：其他工业企业\n\n" +
                            "敏感度评级：中等敏感区域");

            // 历史事故分析
            analysisResult.put("historicalAccidents",
                    "历史事故记录分析（" + factoryName + "）：\n\n" +
                            "近5年事故统计：\n" +
                            "1. 2022年3月：轻微化学品泄漏事件\n" +
                            "   - 影响范围：厂区内部\n" +
                            "   - 处理时间：2小时\n" +
                            "   - 环境影响：无明显影响\n" +
                            "   - 整改措施：已完成设备升级\n\n" +
                            "2. 2021年8月：废水处理设备故障\n" +
                            "   - 影响范围：厂区内部\n" +
                            "   - 处理时间：4小时\n" +
                            "   - 环境影响：无外部影响\n" +
                            "   - 整改措施：已更换设备\n\n" +
                            "3. 2020年以前：无重大事故记录\n\n" +
                            "风险趋势：呈下降趋势，安全管理逐步完善\n" +
                            "应急响应：具备完善的应急预案和处理能力");

            System.out.println("批量分析完成: " + analysisResult);
            return ResultVo.success(analysisResult);

        } catch (Exception e) {
            System.err.println("批量AI分析失败: " + e.getMessage());
            e.printStackTrace();
            return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
        }
    }

    /**
     * 单项AI智能分析接口 - 新增
     * POST /pollution-prediction/ai-smart-analysis/{factoryId}
     */
    @PostMapping("/ai-smart-analysis/{factoryId}")
    public ResultVo aiSmartAnalysis(@PathVariable Long factoryId, @RequestBody Map<String, Object> requestData) {
        try {
            System.out.println("开始单项AI分析，工厂ID: " + factoryId);
            System.out.println("请求数据: " + requestData);

            String analysisType = (String) requestData.get("analysisType");
            Map<String, Object> locationData = (Map<String, Object>) requestData.get("locationData");

            if (analysisType == null || locationData == null) {
                return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
            }

            // 获取工厂信息
            String factoryName = (String) locationData.get("factoryName");
            Object latObj = locationData.get("latitude");
            Object lngObj = locationData.get("longitude");

            String analysisResult = "";

            // 根据分析类型生成不同的结果
            switch (analysisType) {
                case "risk_factors":
                    analysisResult = "基于工厂位置分析（" + latObj + ", " + lngObj + "），主要风险因素包括：\n" +
                            "1. 化学品泄漏风险 - 工厂储存和使用化学原料，存在泄漏风险\n" +
                            "2. 大气污染排放 - 生产过程中可能产生有害气体排放\n" +
                            "3. 土壤污染风险 - 长期生产可能对周边土壤造成污染\n" +
                            "4. 水体污染风险 - 废水处理不当可能影响周边水体\n" +
                            "5. 噪声污染 - 生产设备运行产生的噪声影响";
                    break;
                case "surrounding_environment":
                    analysisResult = "周边环境分析（基于坐标：" + latObj + ", " + lngObj + "）：\n\n" +
                            "1. 500米范围内：居民区约200户，商业区小型店铺\n" +
                            "2. 1000米范围内：学校1所（约500名学生），医院1所\n" +
                            "3. 2000米范围内：水源保护区，农田，其他工业企业\n\n" +
                            "敏感度评级：中等敏感区域";
                    break;
                case "historical_accidents":
                    analysisResult = "历史事故记录分析（" + factoryName + "）：\n\n" +
                            "近5年事故统计：\n" +
                            "1. 2022年3月：轻微化学品泄漏事件（已处理）\n" +
                            "2. 2021年8月：废水处理设备故障（已整改）\n" +
                            "3. 2020年以前：无重大事故记录\n\n" +
                            "风险趋势：呈下降趋势，安全管理逐步完善";
                    break;
                case "impact_scope":
                    analysisResult = "影响范围分析（基于坐标：" + latObj + ", " + lngObj + "）：\n\n" +
                            "1. 直接影响区域（1公里内）：高浓度污染物扩散区域\n" +
                            "   - 需要重点监控和防护\n" +
                            "   - 可能对人体健康造成直接影响\n\n" +
                            "2. 间接影响区域（1-3公里）：中等浓度污染物影响\n" +
                            "   - 需要定期监测\n" +
                            "   - 对敏感人群可能有影响\n\n" +
                            "3. 潜在影响区域（3-5公里）：低浓度长期影响\n" +
                            "   - 需要建立预警机制\n" +
                            "   - 主要影响生态环境\n\n" +
                            "影响等级：中等影响";
                    break;
                case "sensitive_targets":
                    analysisResult = "敏感目标识别（" + factoryName + "周边）：\n\n" +
                            "1. 教育机构：\n" +
                            "   - 小学2所（距离800m、1200m）\n" +
                            "   - 中学1所（距离1500m）\n" +
                            "   - 幼儿园3所（距离600m、900m、1100m）\n\n" +
                            "2. 医疗机构：\n" +
                            "   - 综合医院1所（距离1000m）\n" +
                            "   - 社区卫生服务中心2所\n" +
                            "   - 养老院1所（距离800m）\n\n" +
                            "3. 居住区域：\n" +
                            "   - 大型居民小区5个\n" +
                            "   - 总人口约15000人\n" +
                            "   - 高层住宅为主\n\n" +
                            "4. 生态敏感区：\n" +
                            "   - 城市绿地公园1处\n" +
                            "   - 河流水系1条（距离2000m）\n\n" +
                            "敏感度评级：高敏感区域";
                    break;
                case "population_impact":
                    analysisResult = "人口影响评估：\n\n" +
                            "1. 直接影响人口：\n" +
                            "   - 1公里范围内：约5000人\n" +
                            "   - 主要为居民区和学校师生\n" +
                            "   - 高风险人群：儿童、老人、孕妇\n\n" +
                            "2. 间接影响人口：\n" +
                            "   - 3公里范围内：约20000人\n" +
                            "   - 包括工作人群和流动人口\n" +
                            "   - 需要建立健康监测机制\n\n" +
                            "3. 健康风险评估：\n" +
                            "   - 呼吸系统疾病风险：中等\n" +
                            "   - 皮肤接触风险：低等\n" +
                            "   - 长期暴露风险：中等\n\n" +
                            "4. 防护建议：\n" +
                            "   - 建立应急疏散预案\n" +
                            "   - 定期健康体检\n" +
                            "   - 环境质量实时监测\n\n" +
                            "人口影响等级：中等影响";
                    break;
                case "environmental_impact":
                    analysisResult = "环境影响评估：\n\n" +
                            "1. 大气环境影响：\n" +
                            "   - 主要污染物：SO2、NOx、颗粒物\n" +
                            "   - 影响范围：5公里半径\n" +
                            "   - 影响程度：中等\n\n" +
                            "2. 水环境影响：\n" +
                            "   - 地表水影响：轻微\n" +
                            "   - 地下水影响：需要监测\n" +
                            "   - 水质保护措施：完善\n\n" +
                            "3. 土壤环境影响：\n" +
                            "   - 重金属污染风险：低等\n" +
                            "   - 有机污染物风险：中等\n" +
                            "   - 土壤修复能力：良好\n\n" +
                            "4. 生态环境影响：\n" +
                            "   - 植被影响：轻微\n" +
                            "   - 动物栖息地影响：轻微\n" +
                            "   - 生物多样性影响：可控\n\n" +
                            "5. 噪声影响：\n" +
                            "   - 昼间噪声：符合标准\n" +
                            "   - 夜间噪声：需要控制\n\n" +
                            "环境影响等级：中等影响";
                    break;
                default:
                    analysisResult = "未知的分析类型: " + analysisType;
            }

            Map<String, Object> result = new HashMap<>();
            result.put("analysis", analysisResult);

            System.out.println("单项分析完成: " + analysisResult);
            return ResultVo.success(result);

        } catch (Exception e) {
            System.err.println("单项AI分析失败: " + e.getMessage());
            e.printStackTrace();
            return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
        }
    }

    /**
     * 通用AI分析接口
     * POST /pollution-prediction/general-analysis
     */
    @PostMapping("/general-analysis")
    public ResultVo generalAnalysis(@RequestParam String analysisType, @RequestBody Map<String, Object> parameters) {
        try {
            String analysisResult = aiService.generalAnalysis(analysisType, parameters);

            Map<String, Object> result = new HashMap<>();
            result.put("analysisType", analysisType);
            result.put("parameters", parameters);
            result.put("analysisResult", analysisResult);
            result.put("timestamp", System.currentTimeMillis());

            return ResultVo.success(result);
        } catch (Exception e) {
            return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
        }
    }

    /**
     * 获取预测结果
     * GET /pollution-prediction/result/{predictionId}
     */
    @GetMapping("/result/{predictionId}")
    public ResultVo getPredictionResult(@PathVariable String predictionId) {
        try {
            // 这里可以实现结果缓存或数据库查询
            Map<String, Object> result = new HashMap<>();
            result.put("predictionId", predictionId);
            result.put("status", "completed");
            result.put("message", "预测结果已生成");

            return ResultVo.success(result);
        } catch (Exception e) {
            return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
        }
    }

    /**
     * 生成地理可视化数据
     * @param factoryId 工厂ID
     * @param weatherData 天气数据
     * @return 地理可视化数据
     */
    private Map<String, Object> generateGeoVisualizationData(Long factoryId, Map<String, Object> weatherData) {
        System.out.println("开始生成地理可视化数据，工厂ID: " + factoryId);

        Map<String, Object> geoData = new HashMap<>();

        try {
            // 根据工厂ID获取工厂坐标（这里使用模拟数据）
            Map<String, Object> factoryLocation = getFactoryLocation(factoryId);
            geoData.put("factoryLocation", factoryLocation);
            System.out.println("工厂位置: " + factoryLocation);

            // 不再生成扩散路径射线
            // List<Map<String, Object>> diffusionPath = calculateDiffusionPath(factoryLocation, weatherData);
            // geoData.put("diffusionPath", diffusionPath);
            // System.out.println("扩散路径点数: " + diffusionPath.size());

            // 计算影响范围
            Map<String, Object> impactArea = calculateImpactArea(factoryLocation, weatherData);
            geoData.put("impactArea", impactArea);
            System.out.println("影响范围: " + impactArea);

            // 生成敏感区域
            List<Map<String, Object>> sensitiveAreas = generateSensitiveAreas(factoryLocation);
            geoData.put("sensitiveAreas", sensitiveAreas);
            System.out.println("敏感区域数量: " + sensitiveAreas.size());

            System.out.println("地理数据生成完成: " + geoData);
            return geoData;
        } catch (Exception e) {
            System.err.println("生成地理数据时发生错误: " + e.getMessage());
            e.printStackTrace();
            return geoData;
        }
    }

    /**
     * 安全地转换数值类型
     */
    private double getDoubleValue(Object value) {
        if (value == null) return 0.0;
        if (value instanceof Double) return (Double) value;
        if (value instanceof BigDecimal) return ((BigDecimal) value).doubleValue();
        if (value instanceof Number) return ((Number) value).doubleValue();
        try {
            return Double.parseDouble(value.toString());
        } catch (Exception e) {
            return 0.0;
        }
    }

    /**
     * 获取工厂位置坐标 - 使用真实数据库查询
     */
    private Map<String, Object> getFactoryLocation(Long factoryId) {
        Map<String, Object> location = new HashMap<>();

        try {
            // 使用Mapper直接查询真实工厂数据
            ChemicalFactory factory = chemicalFactoryMapper.selectById(factoryId);

            if (factory != null) {
                location.put("longitude", factory.getLongitude());
                location.put("latitude", factory.getLatitude());
                location.put("name", factory.getFactoryName());
                location.put("address", factory.getAddress());
                location.put("factoryType", factory.getFactoryType());
                location.put("mainPollutants", factory.getMainPollutants());
                System.out.println("查询到工厂数据: " + factory.getFactoryName() + " - " + factory.getAddress());
            } else {
                // 如果查询失败，返回默认值
                location.put("longitude", 113.264385);
                location.put("latitude", 23.129163);
                location.put("name", "未知工厂");
                location.put("address", "未知地址");
                location.put("factoryType", "未知类型");
                location.put("mainPollutants", "未知污染物");
                System.out.println("未找到工厂ID: " + factoryId);
            }
        } catch (Exception e) {
            System.err.println("查询工厂数据失败: " + e.getMessage());
            e.printStackTrace();
            // 异常时返回默认值
            location.put("longitude", 113.264385);
            location.put("latitude", 23.129163);
            location.put("name", "查询失败");
            location.put("address", "查询失败");
            location.put("factoryType", "查询失败");
            location.put("mainPollutants", "查询失败");
        }

        return location;
    }

    /**
     * 计算扩散路径 - 生成扇形扩散区域
     */
    private List<Map<String, Object>> calculateDiffusionPath(Map<String, Object> factoryLocation, Map<String, Object> weatherData) {
        List<Map<String, Object>> pathPoints = new ArrayList<>();

        double factoryLng = (Double) factoryLocation.get("longitude");
        double factoryLat = (Double) factoryLocation.get("latitude");
        String windDirection = (String) weatherData.get("windDirection");
        double windSpeed = ((Number) weatherData.get("windSpeed")).doubleValue();

        // 风向角度映射
        Map<String, Double> directionAngles = new HashMap<>();
        directionAngles.put("北风", 0.0);
        directionAngles.put("东北风", 45.0);
        directionAngles.put("东风", 90.0);
        directionAngles.put("东南风", 135.0);
        directionAngles.put("南风", 180.0);
        directionAngles.put("西南风", 225.0);
        directionAngles.put("西风", 270.0);
        directionAngles.put("西北风", 315.0);

        double centerAngle = directionAngles.getOrDefault(windDirection, 0.0);
        double centerRadians = Math.toRadians(centerAngle);

        // 根据风速计算扩散距离
        double maxDistance = windSpeed * 1000; // 每m/s对应1000米

        // 生成扇形扩散区域 - 多条射线
        int rayCount = 7; // 7条射线形成扇形
        double spreadAngle = 60.0; // 扇形角度60度
        double angleStep = spreadAngle / (rayCount - 1);

        for (int ray = 0; ray < rayCount; ray++) {
            // 计算当前射线的角度
            double currentAngle = centerAngle - spreadAngle/2 + ray * angleStep;
            double currentRadians = Math.toRadians(currentAngle);

            // 为每条射线生成多个点
            for (int i = 0; i <= 8; i++) {
                double distance = (maxDistance * i) / 8;

                // 距离越远，扩散角度越大（模拟扩散效应）
                double spreadFactor = 1.0 + (distance / maxDistance) * 0.3;
                double adjustedAngle = currentAngle + (ray - rayCount/2) * spreadFactor * 2;
                double adjustedRadians = Math.toRadians(adjustedAngle);

                double lngOffset = distance * Math.sin(adjustedRadians) / 111000;
                double latOffset = distance * Math.cos(adjustedRadians) / 111000;

                Map<String, Object> point = new HashMap<>();
                point.put("longitude", factoryLng + lngOffset);
                point.put("latitude", factoryLat + latOffset);
                point.put("distance", distance);
                point.put("concentration", Math.max(0, 100 - (distance / 50))); // 浓度递减
                point.put("ray", ray); // 标记属于哪条射线

                pathPoints.add(point);
            }
        }

        return pathPoints;
    }

    /**
     * 计算影响范围 - 生成椭圆形影响区域
     */
    private Map<String, Object> calculateImpactArea(Map<String, Object> factoryLocation, Map<String, Object> weatherData) {
        Map<String, Object> impactArea = new HashMap<>();

        // 安全地获取坐标值，处理BigDecimal类型
        double factoryLng = getDoubleValue(factoryLocation.get("longitude"));
        double factoryLat = getDoubleValue(factoryLocation.get("latitude"));
        String windDirection = (String) weatherData.get("windDirection");
        double windSpeed = getDoubleValue(weatherData.get("windSpeed"));

        // 风向角度映射
        Map<String, Double> directionAngles = new HashMap<>();
        directionAngles.put("北风", 0.0);
        directionAngles.put("东北风", 45.0);
        directionAngles.put("东风", 90.0);
        directionAngles.put("东南风", 135.0);
        directionAngles.put("南风", 180.0);
        directionAngles.put("西南风", 225.0);
        directionAngles.put("西风", 270.0);
        directionAngles.put("西北风", 315.0);

        double windAngle = directionAngles.getOrDefault(windDirection, 0.0);

        // 计算影响范围（米）- 简化为圆形
        double radius = Math.min(windSpeed * 500, 1000); // 限制最大半径为1000米

        // 生成圆形边界点（16个点，减少复杂度）
        List<Map<String, Object>> circlePoints = new ArrayList<>();
        int pointCount = 16; // 圆形上的点数

        for (int i = 0; i < pointCount; i++) {
            double angle = 2 * Math.PI * i / pointCount;

            // 圆形参数方程
            double x = radius * Math.cos(angle) / 111000; // 转换为经纬度
            double y = radius * Math.sin(angle) / 111000;

            Map<String, Object> point = new HashMap<>();
            point.put("longitude", factoryLng + x);
            point.put("latitude", factoryLat + y);

            circlePoints.add(point);
        }

        impactArea.put("center", factoryLocation);
        impactArea.put("radius", radius);
        impactArea.put("windAngle", windAngle);
        impactArea.put("circlePoints", circlePoints);
        impactArea.put("area", Math.PI * radius * radius); // 圆形面积

        // 添加圆圈数据
        Map<String, Object> circle = new HashMap<>();
        circle.put("longitude", factoryLng);
        circle.put("latitude", factoryLat);
        circle.put("radius", radius);
        circle.put("strokeColor", "rgba(231, 76, 60, 0.9)"); // 改成 strokeColor
        circle.put("fillColor", "rgba(231, 76, 60, 0.4)"); // 增强填充色 - 红色
        circle.put("strokeWidth", 6); // 增加边框宽度
        impactArea.put("circle", circle);

        return impactArea;
    }

    /**
     * 生成敏感区域
     */
    private List<Map<String, Object>> generateSensitiveAreas(Map<String, Object> factoryLocation) {
        List<Map<String, Object>> sensitiveAreas = new ArrayList<>();

        // 安全地获取坐标值，处理BigDecimal类型
        double factoryLng = getDoubleValue(factoryLocation.get("longitude"));
        double factoryLat = getDoubleValue(factoryLocation.get("latitude"));

        // 模拟敏感区域
        Map<String, Object> school = new HashMap<>();
        school.put("type", "school");
        school.put("name", "附近小学");
        school.put("longitude", factoryLng + 0.01);
        school.put("latitude", factoryLat + 0.01);
        school.put("distance", 1000);
        sensitiveAreas.add(school);

        Map<String, Object> hospital = new HashMap<>();
        hospital.put("type", "hospital");
        hospital.put("name", "附近医院");
        hospital.put("longitude", factoryLng - 0.01);
        hospital.put("latitude", factoryLat + 0.01);
        hospital.put("distance", 1200);
        sensitiveAreas.add(hospital);

        Map<String, Object> residential = new HashMap<>();
        residential.put("type", "residential");
        residential.put("name", "居民区");
        residential.put("longitude", factoryLng + 0.005);
        residential.put("latitude", factoryLat - 0.01);
        residential.put("distance", 800);
        sensitiveAreas.add(residential);

        return sensitiveAreas;
    }

}
